Skip to main content

Basics

A Python program like all other languages is a collection of blocks of code, ranging from classes (object definitions) and their methods, functions and everything inbetween.

Let's get started.

In PyCharm if you open main.py in your new project. You will see the following:

Note if you do not see this, because you are using a different IDE, you can just create a new python file and copy this, or simply read on.

def print_hi(name):
print(f'Hi, {name}')


if __name__ == '__main__':
print_hi('PyCharm')

There are two parts to this basic python code.

  1. The top part is a function. All functions, except for some built-in python functions, are declared by the def keyword before a function name, in this case the functions is called 'print_hi'. Every function has some code, this is the body of the function. Python uses strict indentation rules (generally 4 spaces or a tab) to indent code correctly. As can be seen the body of this function print(f'Hi, {name}') is indented. The 'print' function is a built-in python function that outputs a string to the screen (console).

  2. The second part is the python __main__ function. This is where the python interpreter identifies the start of the code to be run. In its body is a call to the function above it print_hi. When the interpreter runs the program it will immediately run the __main__ function.

Run the program and see what happens

Now let's change the program to the following:

def print_hi(name):
print(f'Hi, {name}')

if __name__ == '__main__':
my_name = input("Please enter your name: ")
print_hi(my_name)

We've introduced a standard python input function that prompts for some input via the screen and returns that input as a string. In this case, it will ask you for your name. The input function is on a separate line to the print_hi function. In Python, it's normal to place each statement, e.g. line of code on a separate line. It is possible to separate statements with a ; but this is not to be encouraged.

Sometimes when a line of code is too long you can split it between two or more lines with a \ at the end of each line.

Whilst functions are very useful for splitting code into relevant chunks, Python does not require you to use them. You can write a sequential flow of code without using functions. This is often the case when Python is used for writing short scripts that do useful utility work.

    my_name = input("Please enter your name: ")
print(f'Hi, {my_name} \n')
print("have a great day!")

Run the code again, type your name and press enter.

Comments

Comments in python start with a hash symbol # and should be followed by a space and then the comment. You can see a comment above the __main__ function below. Multi-line comments in Python can be achieved by using two sets of """ quotes to wrap the comments in. These are also used when producing what are called doc strings. Doc strings are comments that are made before the body of the function or class. They are enclosed in triple double quotation marks """Doc String""" and can be multiple lines long. Doc string are mainly used to document functions and classes and can be used to auto generate documentation. Below is an example:

def print_hi(name):
"""
My print function
"""
print(f'Hi, {name}')

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
my_name = input("Please enter your name: ")
"""
A multi-line
comment
"""
print_hi(my_name)

Literals and Variables

A literal in python, as in other programming languages, represents a fixed value. For example, 10, 5.32, -3 are numeric literals, True and False are boolean literals, and "Istanbul" is a string literal.

Variables are labels/names for memory slots ( a piece of memory used to contain some data) that contain a literal value assigned to it at some point in the code sequence.

In the line of code:

my_name = input("Please enter your name: ")

my_name is a variable. When the user inputs their name, the variable my_name is assigned as a pointer in memory to the literal entered by the user. Python takes care of that.

We then use that variable name to pass the data in memory to the print_hi function. It takes the value from memory via the variable pointer and prints it on the screen.

NOTE: Unlike a lot of other programming languages, there is no concept of a fixed constant variable in Python. All variables can be assigned different values at anytime.

Naming Variables

There are syntax rules (rules that define how we write our code, style and formatting) regarding variable names in Python. Below is a list of legal and illegal variable names:

#Legal variable names
varname = "Richard"
var_name = "Richard"
_var_name = "Richard"
varName = "Richard"
VARNAME = "Richard"
varname2 = "Richard"
VarName = "Richard"

#Illegal variable names
2varname = "Richard"
var-name = "Richard"
var name = "Richard"

However, despite the above, by convention, we use names that are lowercase and separate words with an '_', i.e. var_name.

Try changing my_name to My_name and your IDE should highlight that in some fashion and suggest changing it to lowercase.

Private Variables

In programming languages, private variables are those that only part of the code (a class, module) can see and modify; for example, they are used to hide certain information from rest of the program.

Python has a limited scope for using private variables. There is no syntactical rule for private variables in python, again, it's more of a convention. Private variables can be represented by using double underscores at the beginning of the name i.e. __my_private_variable. Normally, private variables are used in classes or class methods and not as a general rule in functions.

To sum up, we can use both literals and variables to refer to values. The difference is, when we use a literal we use the actual value directly without wrapping it in a variable. Generally we would use literals when the value is concrete, unchangeable (immutable), in a static formula etc.

For example, when we write 10 + 20, literally we are simply adding two literal values together to come up with the value 30. If we assign these values to two variables, i.e. number1 + number2, we are adding the two values contained in the memory slots pointed to by those variables.

Declaring and Assigning Variables

In Python, we do not use a special keyword to indicate that we are defining a variable, and we always provide a variable with some value during declaration. either the value you want it to hold or a temporary value. The use of None in Python indicates that the variable has no value.

number1 = 100
number2 = None

None does not mean 0 or False it means simply no value. Its uses vary from checking incoming variables from one function to resetting variables to have no value until assigned once more.

You can assign either a single value to a variable or multiple values to multiple variables on one line. Assignment is performed by using the = operator.

my_name = 'Richard'
my_birth_day, my_birth_month = 1, 9
print(my_name, my_birth_day, my_birth_month)

Above, we have assigned a single value to my_name, the string "Richard" and the value 1 and 9 to my_birth_day and my_birth_month respectively.

Notice also that we can assign more than one argument to the print function.

Global vs Local Variables

In Python, variables can store primitive values (strings, numbers, booleans etc.), as well as objects, and functions. If a variable is declared inside a function it is a local variable accessible only within the function body.

A global variable is defined outside any function or class and can be directly used by any function by declaring it with the global prefix before assigning it. You can import global variables into other module by importing it into that module explicitly.


MY_GLOBAL = None

def some_function(x):
global MY_GLOBAL
MY_GLOBAL = x ** 2

some_function(2)
print(MY_GLOBAL)

Without the prefixed global statement the MY_GLOBAL variable in the some_function function would be seen as a local variable and the print statement would print None

Note for easy identification the global variable is written in uppercase.

Basic Data types

Strings

In our example using the input, the input function returns a string my_name which points to a string value in memory. A string is a sequence of characters, such as "Istanbul" or "Hello World". Strings are used to process textual data, ASCII, UTF-8... Under the hood, Python strings are actually a sequence of unicode code points, but in memory everything is stored in bytes. In Python 3 a string is literally like anything else in memory - bytes. The intricacies of this can be discovered on the Internet by those that wish to dive in deeper.

A couple of interesting write-ups here Python Strings and here Python Strings

String literals are surrounded by single or double quotes or triple single or triple double quotes. There is no difference in using them, under the hood they will result in the same data in memory. Below, all five variables contain the same data regardless of how they are quoted. If the quotes are different types you'll get a syntax error. It is a good practice to use the same type of quote for strings throughout your software. A general rule of thumb is to use ' single quotes for string literals and " double quotes for string phrases. If a string phrase itself contains a double quote that double quote can be escaped, we'll get to that later, or you can wrap the phrase in single quotes and visa versa.

# legal string assignments
example1 = 'Tayfun'
print(example1)
example2 = "Tayfun"
print(example2)
example3 = '''Tayfun'''
print(example3)
example4 = """Tayfun"""
print(example4)
legal_but_bad = "Tayfun"""

# illegal string assignment
bad = "Tayfun'
bad2 = "Tayfun'

When you print a string, it is always printed without the quotation marks, unless the quotation marks are themselves wrapped in other quotations marks such as when using an apostrophe. This

example = "Richard's book"
print(example)

String wrapping quotation marks are not part of the string value, they are just language constructs that define a value as a string.

For example: the len() function gives us the length of the string (the number of characters in the string). If we print the length of the string, you will see that it does not count the quotes.

name = 'Tayfun'
print(len(name))
book = "Richard's book"
print(len(book))

Note, In the second print statement the space is counted as a character.

Escaping Strings

In strings, a backslash '\' is a special escaping character. Escaping refers to marking a character with special meaning. For example the following assignment is invalid because we are using double quotes to quote a word in the string we are assigning.

txt = "We are the "Coders" from the north."

To get the interpreter to include the quotation marks in the string as part of the string we can escape those quotation marks thus

txt = "We are the \"Coders\" from the north."

The above '\' tells the interpreter that the character after it should be treated as a special character - in this case a quotation as part of the string.

We could of course assign the string phrase as follows:

txt = 'We are the "Coders" from the north.'

Sometimes we require one or more \ in the string, for example, when defining a path: "My home path is C:\Users\tayfun" In this case we have a couple of options

  1. Add another '\' in front of those backslashes we require as part of the string, "My home path is C:\\Users\\tayfun"
  2. Adding an r at the beginning of the string r"My home path is C:\Users\tayfun" tells us that what you see is what we get.

There are a number of common escape characters that we will come across in everyday string manipulation. Amongst these are

  • \n - indicates a new line follows the previous content of a string. For example, print("Hello\nWorld") will print World on a new line.
  • \r - Indicates a 'carriage return' after the previous content of a string. This can conventionally be covered by the above \n. carriage returns work differently under different operating systems
  • \t - Indicates a 'tab' space after some text, print("Hello\tWorld")

Multi-line Strings

Triple quotation marks allow the use of multi-line strings. A prime example is 'Doc Strings' that are used to define function and class descriptions, other examples might be help strings or drawing shapes:

help_string = """
Usage: mysql command
-h hostname
-d database name
-u username
-p password
"""
print(help_string)

String Concatenation

There are numerous ways to concatenate (join) strings together.

  1. The + operator
print("Richard's "  + 'Macbook')

Note, concatenation of strings using the + operator is not memory efficient. Because strings are immutable, Python has to allocate new memory for every concatenation. use the join() or string format functions or the % operator.

  1. built-in join function
# String concatenation using join and a list of string literals or variables
laptop = "Macbook"
print(" ".join(["Tayfun's ", laptop]))
  1. The % operator
print("%s and %s both have %s" % ("Richard", "Tayfun", "Macbooks"))

The example above uses string literals, but you can use variables in their place.

name1 = "Richard"
name2 = "Tayfun"
print("%s and %s both have %s" % (name1, name2, "Macbooks"))

Formatting Strings

Similar to concatenation we sometimes want to add one or more variables directly into a string. For this we can use the f operator in front of the string. We can include a variable in curly brackets {...} and the value of that variable will be injected into the string. For example:

name = "Tayfun"
numHours = 10
message = f'Hi {name}, you have {numHours} minutes to reply this message'

Accessing string characters and slicing strings

Sometimes it is necessary to extract part of a string, a substring, or work with the characters of a string.

In the example below we are assigning a string to the variable name, printing the length of that string, i.e. the number of characters in the string, and then printing each character by its position/index by operating on the string as a list of characters. Don't worry about lists and indexes, we'll get to those later.

## Indices
# I s t a n b u l
# 0 1 2 3 4 5 6 7
name = "Istanbul"
print(len(name)) # length is 8, we can access indices from 0 to 7, python lists are indexed from 0 not 1.
print(name[0]) # I
print(name[1]) # s
print(name[2]) # t
print(name[3]) # a
print(name[4]) # n
print(name[5]) # b
print(name[6]) # u
print(name[7]) # l
print(name[8]) # IndexError: string out of range!

We can expand this syntax to extract a subset of characters, e.g. a substring of the string using a built-in function called slice. To slice a string you add [] square brackets to the string name and inside the square brackets you can specify numerical positions (indexes) of characters - from and to. These are separated by a colon :

name = "Mugla Fethiye" # Province and City
province = name[0:5] # From index 0 (inclusive) to 6 (exclusive).
city = name[6:13] # From index 6 (inclusive) to 13 (exclusive)
print(province) # Mugla
print(city) # Fethiye

# Beginning and ending indexes may be omitted
province = name[:5]
city = name[6:]
print(province) # Mugla
print(city) # Fethiye

The slice function can, if required, skip certain characters. For example, if we write, name[0:10:2] it tells the function to take every second character from index 0 to 9, so for the example above, name[0:10:2] the result would be "MgaFt". We can even reverse the slice by using a negative number in the third slot, i.e. name[10:0:-1] returns "ihteF algu". Notice that the first index here is still the start index, so we start from index 10, and then go backwards by 1, until we reach index 0 (exclusive, so there is no "M"). Using this approach we can reverse a string: name[::-1].

An interesting example is to check if a word is a palindrome (a word that reads the same forwards and backwards), such as "racecar" or "madam".

word = "racecar"
print(word == word[::-1]) # True
word = "Istanbul"
print(word == word[::-1]) # False

Numbers

In Python numbers can be integers or floats (floating point numbers). A float is a number with a fractional part, and can have varying decimal places. Computers cannot represent all fractions (for example, PI) so it uses a special representation called floating point.

For more details on floating point numbers, see Floating Point Numbers

Integers are just whole numbers e.g. 20, 98, 2104...

Floats are represented using a dot before the fractional part, 100.10, 1.5, 25.4...

my_age = 40
my_weight = 85.32
a_half = .5

If the number is a fraction of 0 we can skip the 0 from the whole part, as per the last line above.

Using number literals and variables, we can write arithmetic expressions, a calculation, using values (literals or variables) and operators.

celsius = 30
# Convert this to fahrenheit
fahrenheit = (celsius * 1.8000) + 32
print(fahrenheit)

Arithmetic and Assignment Operators

Arithmetic operators

Arithmetic operators are used to write expressions over numbers:

x = 10
y = 2
print(f"Negation: -x = {-x}")
print(f"Addition: x + y = {x + y}")
print(f"Subtraction: x - y = {x - y}")
print(f"Addition: x * y = {x * y}")
print(f"Division: x / y = {x / y}")
print(f"Remainder (mod): x % y = {x % y}")
print(f"Exponentiation: x ** y = {x ** y}")

Assignment operators

in Python assigning values to variables can be done in long-hand or shorthand expressions. Python has a list of useful assignment shorthand operators that allow various forms of assignment: A few examples are shown below:

x = 5 # Standard assignment
x += 5 # Shorthand of x = x + 5
x -= 2 # Shorthand of x = x - 2
print(x)

x *= 2 # Shorthand of x = x * 2
x /= 2 # Shorthand of x = x / 2
print(x)

The above are all standard ways of assignment. For a comprehensive list of all Python operators see Python Operators

Booleans

Computers are built on top of boolean logic, the sense that something is true or false, open or closed, active or inactive...

Boolean values in Python are True and False. Notice that the first letter is uppercase.

is_working = True
is_flying = False

You can use the built-in bool() function to see if a variable or literal is True or False.

# Will all evaluate to True
bool(True)
bool("hello")
bool(10)

# Values such as 0 and False as well as empty objects will all evaluate to False
bool(0)
bool('')
bool(False)
bool([])

Type conversions

Sometimes we need to convert values to other data types. In Python, there is no implicit type conversion, so we need to call special functions to do conversion.

We use type conversion to convert different data types depending on where the data is used, the input and output and data manipulation. Consider our previous example using an input to get data from the user. The data we retrieve as a string is not useful if we need to do some maths on it. To get the data type of a literal or variable, you can use the built-in function type().

Examples:

print(type(1))
word = "Hello"
print(type(word))
print(type(100.3))
print(type("100.3"))
print(type(True))

The above will output the following:

<class 'int'>
<class 'str'>
<class 'float'>
<class 'str'>
<class 'bool'>

Let's take a look at some type conversions

if __name__ == '__main__':
teachers_age = 40
students_age = input("Please enter your age: ")
if students_age < teachers_age:
print("You are younger than your teacher")

This code will throw a TypeError, one of pythons built in errors. Even though the user typed in a number, the input function has converted it to a string. Our code is attempting to compare a string (the user input) with an integer number. Python won't allow cross type expressions, hence the error.

TypeError: '<=' not supported between instances of 'int' and 'str'

The way around this is a quick conversion of the input to an integer:

if __name__ == '__main__':
teachers_age = 40
students_age = input("Please enter your age: ")
if int(students_age) < teachers_age:
print("You are younger than your teacher")

Above we have forced a type conversion on the variable students_age from a string to an integer by using the built-in function int() We can now treat it as an integer and use it in numerical expressions.

If we need to output the result as a string it's no problem as we still have the original string in the variable students_age. However, we might need to do some more maths from the input. Let's calculate how many years until the student is 100 years old.

if __name__ == '__main__':
students_age = input("Please enter your age: ")
until_hundred = 100 - int(students_age)

print("You are going to be 100 in " + str(until_hundred) + " years")

In the above code, the variable until_hundred is automatically designated as an integer type because of the values in the expression from which it takes its value. However, what happens if the user inputs a floating point number, for example '33.5'?

We get the following ValueError

ValueError: invalid literal for int() with base 10: '33.5'

In order to fix this so that it makes no difference if the user puts in a whole number or a number with a decimal place we would convert to a float instead of int

if __name__ == '__main__':
students_age = input("Please enter your age: ")
until_hundred = 100 - float(students_age)

print("You are going to be 100 in " + str(until_hundred) + " years")

The only difference is that the output years will contain a decimal place, e.g. 66.5. This is easily remedied by rounding up or down and simultaneously converting the floating point to an integer.

if __name__ == '__main__':
students_age = input("Please enter your age: ")
until_hundred = 100 - float(students_age)
until_hundred = int(round(until_hundred, 0))
print(f"You are going to be 100 in {until_hundred} years")

Notice that we did not need to convert until_hundred from an integer to a string when we printed. Our string format command and the inclusion of our variable in curly brackets performed the type conversion for us.

print("You are going to be 100 in " + str(until_hundred) + " years")

Here we have converted until_hundred to a string with the built-in function str().

In the above examples we have used the int(), float(), str() type conversion functions.

For a full list of Pythons built-in type conversion functions are listed here Python Data Type conversion

Resources

That's it for this section, you can move on to the next part of this tutorial.